<?php
namespace app\common\model;

use \think\Db;

class CourseRoom extends \think\Model
{
    protected $visible = ['id', 'name', 'teacher', 'class_name', 'term_id', 'week', 'class_week', 'class_time', 'room', 'student_count'];

    public function getClassWeekStrAttr()
    {
        return bitmapToStr($this->getAttr('class_week'));
    }

    public function getClassTimeStrAttr()
    {
        return bitmapToStr($this->getAttr('class_time'));
    }

    public static function scheduleAdvise($termId, $week, $classWeek, $classTime,$building)
    {
        if ($building) {
            $roomNames = db('room')->where('building', $building)->column('name');
        } else {
            $roomNames = db('room')->column('name');
        }

        $table = [];
        foreach ($roomNames as $room) {
            $conflictTime = 0;
            $conflict = CourseRoom::where([
                ['room', '=', $room],
                ['term_id', '=', $termId],
                ['week', '=', $week],
                ['', 'exp', Db::raw('(class_week&' . $classWeek . ')<>0 and (class_time&' . $classTime . ')<>0')],
            ])->select();
            if (count($conflict)) {
                //存在碰撞
                $max = bitmapCountBit($classTime) *bitmapCountBit( $classWeek);
                foreach ($conflict as $v) {
                    $conflictTime += bitmapCountBit($classWeek & $v->class_week) * bitmapCountBit($classTime & $v->class_time);
                    if ($conflictTime >= $max) {
                        break;
                    }
                }

                if ($conflictTime >= $max) {
                    \array_push( $table ,[
                        'room' => $room,
                        'ratio' => 0,
                    ]);
                } else {
                    \array_push( $table ,[
                        'room' => $room,
                        'ratio' =>100- $conflictTime / $max * 100,
                    ]);
                }
            } else {
                \array_push( $table , [
                    'room' => $room,
                    'ratio' => 100,
                ]);
            }
        }

        \usort($table,function ($a,$b){
            return $b['ratio']-$a['ratio'];
        });

        return $table;
    }

}
